<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Cache;
use Log;
use Redis;

class QingPingController extends Controller
{
    /*删除一周以前的温湿度大气压*/
    public function delEnvInfo()
    {
        $date = date('Y-m-d', strtotime('-7day'));
        DB::table('a_env_info')->whereDate('time', '<', $date)->delete();
    }

    /* 获取青萍温湿度气压计的数据 */
    public function getData(Request $request)
    {
        // dd($this->get_device_list());
        // Log::info('青萍温湿度气压计--获取数据'); //该方法会将日志全部记录在 storage/logs/laravel.log 文件里，这样的问题是当日志文件比较多的时候查找起来比较麻烦
        // Log::info($request->all()); //该方法会将日志全部记录在 storage/logs/laravel.log 文件里，这样的问题是当日志文件比较多的时候查找起来比较麻烦
        $app_names = get_databases();

        $fullData = $this->get_device_list();
        $data = $fullData['devices'];
        // dd($fullData);
        if ($data) {
            # $data 不为 null 就进行 foreach

            foreach ($data as $k => $v) {
                $timestamp = $v['data']['timestamp']['value'];
                if ((time() - $timestamp) > 60 * 25) {
                    # 此设备已离线
                    continue;
                }
                $temp = $v['data']['temperature']['value'];
                $temp = sprintf("%.1f", $temp);
                $humi = $v['data']['humidity']['value'];
                $humi = sprintf("%.1f", $humi);
                $pressure = $v['data']['pressure']['value'];
                $pressure = sprintf("%.2f", $pressure);
                $dev_num = $v['info']['mac'];
                $time = date("Y-m-d H:i:s", $timestamp);
                foreach ($app_names as $appName) {
                    # code...

                    $hb6303_id = DB::connection("mysql_{$appName}")->table('a_hb6303')->where('dev_num', $dev_num)->value('id');
                    if ($hb6303_id) {
                        # code...
                        DB::connection("mysql_{$appName}")->table('a_env_info')->insert([
                            'temp'      => $temp,
                            'humi'      => $humi,
                            'pressure'  => $pressure,
                            'dev_num'   => $dev_num,
                            'time'      => $time,
                            'hb6303_id' => $hb6303_id
                        ]);
	                    DB::connection("mysql_{$appName}")->table('a_env_info')->whereDate('time','<',date('Y-m-d H:i:s',strtotime('-7 days')));
                    }
                }
            }
        }

        return 'ok';
    }

    /* 获取设备列表 */
    public function get_device_list()
    {
        $access_token = $this->getAccessToken();
        $timestamp = msectime();
        // $limit = 200;
        $url = "https://apis.cleargrass.com/v1/apis/devices?timestamp={$timestamp}";

        $header = [
            "Authorization:Bearer $access_token"
        ];

        $res = $this->send_get($url, $header);
        $this->device_list_save_redis($res); //将设备列表存入 redis
//        dd($res);
        return $res;
    }

    /* 将设备列表存入 redis */
    private function device_list_save_redis($data)
    {
        $redis = Redis::connection('public');
        $seconds = 60 * 15; //token缓存的时间，单位 秒
        $json = json_encode($data);//数组转json串
        $redis->set('qingping_device_list', $json, 'EX', $seconds);
    }

    //获取access_token
    private function getAccessToken()
    {
        // access_token的有效期目前为2个小时，需定时刷新，重复获取将导致上次获取的access_token失效，所以多个项目的access_token缓存要共用

        $redis = Redis::connection('public');

        $seconds = 60 * 60; //token缓存的时间，单位 秒，微信服务器2小时过期
        if ($redis->exists('qingping_access_token') === 0) {
            # 缓存不存在，访问微信接口获取access_token
            $appKey = config('constant.qingping_app_key');
            $appSecret = config('constant.qingping_app_secret');
            $username_pwd = base64_encode("{$appKey}:{$appSecret}");

            $header = [
                "Content-type:application/x-www-form-urlencoded",
                "Authorization:Basic $username_pwd"
            ];

            $post_data = [
                'grant_type' => 'client_credentials',
                'scope'      => 'device_full_access'
            ];

            $url = "https://oauth.cleargrass.com/oauth2/token";

            $arr_access_token = $this->send_post($url, $header, $post_data);
            $access_token = $arr_access_token['access_token'];
            $redis->set('qingping_access_token', $access_token, 'EX', $seconds);
        }
        else {
            # 缓存存在
            $access_token = $redis->get('qingping_access_token');
        }
        return $access_token;
    }

    /* 获取单个设备的历史数据 */
    private function get_history_data()
    {
        $access_token = $this->getAccessToken();
        $mac = "582D3446075D";
        $start_time = time() - 12 * 60 * 60;
        $end_time = time() + 60 * 60;
        $timestamp = msectime();
        $limit = 200;

        $url = "https://apis.cleargrass.com/v1/apis/devices/data?mac={$mac}&end_time={$end_time}&limit={$limit}&start_time={$start_time}&timestamp={$timestamp}";

        $header = [
            "Authorization:Bearer $access_token"
        ];

        return $this->send_get($url, $header);
    }

    public function getHisdata()
    {
        $mac = request()->input('mac', '');
//        $mac = "582D344607AD";
        $start_time = request()->input('start_time', '');
        $end_time = request()->input('start_time', '');

        if (!$mac || !$start_time || !$end_time) {
            return out(0, '缺少参数！');
        }
        $start_time = strtotime($start_time);
        $end_time = strtotime($end_time);

        $access_token = $this->getAccessToken();
        $timestamp = msectime();
        $limit = 200;

        $url = "https://apis.cleargrass.com/v1/apis/devices/data?mac={$mac}&end_time={$end_time}&limit={$limit}&start_time={$start_time}&timestamp={$timestamp}";

        $header = [
            "Authorization:Bearer $access_token"
        ];
        $res = $this->send_get($url, $header);

        return response()->json($res);
    }


    /* 发送post请求 */
    private function send_post($url, $header, $postdata)
    {
        $postdata = http_build_query($postdata);

        $options = [
            'http' => [
                'method'  => 'POST',
                'header'  => $header,
                'content' => $postdata,
                'timeout' => 15 * 60 // 超时时间（单位:s）
            ]
        ];

        $context = stream_context_create($options);
        $json = file_get_contents($url, false, $context);
        $arr = json_decode($json, true);
        return $arr;
    }

    /* 发送get请求 */
    private function send_get($url, $header)
    {
        $options = [
            'http' => [
                'method'  => 'GET',
                'header'  => $header,
                'timeout' => 15 * 60 // 超时时间（单位:s）
            ]
        ];

        $context = stream_context_create($options);
        $json = file_get_contents($url, false, $context);
        $arr = json_decode($json, true);
        return $arr;
    }
}
